from django.shortcuts import render, redirect
# 导包
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
# 导入类视图
from django.views import View

import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

import requests

# 导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

# 导入原生sql模块
from django.db import connection

import jwt

# 导入时间模块
import time

# 导入公共目录变量
from mydjango.settings import BASE_DIR

# 导包
from django.db.models import Q, F

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

# 导入序列化对象
from myapp.myser import UserSerializers, PicSer
# 导表
from myapp.models import User, Pics

# 导入redis数据库
import redis

# 定义地址和端口
host = '127.0.0.1'
port = 6379

# 建立redis连接
r = redis.Redis(host=host, port=port)


# 幻灯片接口
class PicsList(APIView):

    def get(self, request):
        # 查询数据
        pics = Pics.objects.filter().values('title', 'link', 'img')
        # 序列化对象
        pics_ser = PicSer(pics, many=True)

        return Response(pics_ser.data)


# 查询所有数据返回到前端展示
class GetData(APIView):

    def get(self, request):
        data = Pics.objects.all()
        res = {}
        list = []
        for i in data:
            list.append({
                'id': i.id,
                'title': i.title,
                'link': i.link,
                'image': i.img
            })

        res['list'] = list
        return Response(res)


# 添加活动数据
class InsertPics(APIView):
    def post(self, request):
        img = request.FILES.get('img')
        title = request.POST.get('title')
        link = request.POST.get('link')
        image = img.name
        pics = Pics.objects.filter(title=title).first()
        if pics:
            return Response({
                'code': 405,
                'message': '该活动已存在，不可重复添加!'
            })
        else:
            # 建立文件流对象
            f = open(os.path.join(UPLOAD_ROOT, '', img.name), 'wb')
            # 写入服务器
            for chunk in img.chunks():
                f.write(chunk)
            f.close()

            Pics.objects.create(title=title, link=link, img='http://127.0.0.1:8000/static/upload/' + image)
            return Response({
                'code': 200,
                'message': '添加成功'
            })


# 删除活动数据
class DeletePics(APIView):

    def post(self, request):
        title = request.POST.get('title')
        print(title)
        pics = Pics.objects.filter(title=title).first()
        if pics:
            Pics.objects.filter(title=title).delete()
            return Response({
                'code': 200,
                'message': '删除成功'
            })
        else:
            return Response({
                'code': 405,
                'messaeg': '该活动不存在'
            })


# 修改活动数据
class UpdatePics(APIView):

    def post(self, request):
        id = request.POST.get('cid')
        title = request.POST.get('title')
        link = request.POST.get('link')
        img = request.FILES.get('img')
        print(id, title, link, img)
        pics = Pics.objects.filter(title=title).first()
        if pics:
            return Response({
                'code': 203,
                'message': '您修改后的活动已存在，请重新修改活动名称！'
            })
        else:
            f = open(os.path.join(UPLOAD_ROOT, '', img.name), 'wb')
            # 写入服务器
            for chunk in img.chunks():
                f.write(chunk)
            f.close()

            Pics.objects.filter(pk=id).update(title=title, link=link, img=img)
            return Response({
                'code': 200,
                'message': '修改成功'
            })
